package com.rogers.monster.service.impl;

import java.util.Arrays;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.rogers.monster.auth.AppUser;
import com.rogers.monster.dao.UserDao;

public class UserDetailsServiceImpl implements UserDetailsService {

    private UserDao userDao;

	public UserDetailsServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {
        AppUser user = userDao.findUser(username);
        if (user == null)
            throw new UsernameNotFoundException("User not found: " + username);
        else {
        	UserDetails ud= makeUser(user);
        	return ud;
        }
    }

    
    private UserDetails makeUser(AppUser user) {
            return new User(user.getLogin(), user
                    .getPassword(), true, true, true, true,
                    makeGrantedAuthorities(user));
        }

        private List<GrantedAuthority> makeGrantedAuthorities(AppUser user) {
            GrantedAuthority[] result = new GrantedAuthority[user.getRoles().size()];
            int i = 0;
            for (String role : user.getRoles()) {
                result[i++] = new GrantedAuthorityImpl(role);
            }
            
           List rl=( result  == null ? null : Arrays.asList(result));
            return rl;
        }

}
